#include "SocketHttpAdapter.h"

#include <QtNetwork/QTcpServer>
#include <QtNetwork/QTcpSocket>
#include <QStringList>

namespace As {

SocketHttpAdapter::SocketHttpAdapter(const QString &host, int port,
                             bool startListen, QObject *parent) :
    AbstractHttpAdapter(parent),
    m_host(host),
    m_port(port)
{
    connect(&m_server, SIGNAL(newConnection()), this, SLOT(newConnection()));
    if (startListen) {
        listen();
    }
}

SocketHttpAdapter::~SocketHttpAdapter() {
}

void SocketHttpAdapter::newConnection() {
    qDebug() << "new incoming connection";
    QTcpSocket* s = m_server.nextPendingConnection();
    connect(s, SIGNAL(readyRead()), this, SLOT(readClient()));
    //connect(s, SIGNAL(disconnected()), this, SLOT(discardClient()));
    m_socketMap[s] = "";
}

void SocketHttpAdapter::readClient() {
    // This slot is called when the client sent data to the server. The
    // server looks if it was a get request and sends a very simple HTML
    // document back.
    QTcpSocket* socket = (QTcpSocket*)sender();
    while (socket->canReadLine()) {
        QString line = socket->readLine();
        m_socketMap[socket] += line.remove(QRegExp("[\r\n]")) + "\n";
    }
    if (m_socketMap[socket].endsWith("\n\n") && m_socketMap[socket].startsWith("GET")) {
        HttpRequest req;
        QMap<QString, QString> map;
        QStringList list = m_socketMap[socket].split(QRegExp("[\r\n][\r\n]*"));
        list.removeFirst();
        for (QStringList::iterator it = list.begin(); it != list.end(); ++it) {
            QStringList line = it->split(": ");
            if (line.size() > 1) {
                map[line[0]] = line[1];
            }
        }
        req.m_headerMap = map;
        req.m_socket = socket;
        emit request(req);
        qDebug() << "got GET request";
    }
}

void SocketHttpAdapter::discardClient() {
    QTcpSocket* socket = (QTcpSocket*)sender();
    socket->deleteLater();
}

void SocketHttpAdapter::listen() {
    m_server.listen(QHostAddress(m_host), m_port);
}

void SocketHttpAdapter::stopListen() {
    m_server.close();
}

void SocketHttpAdapter::response(As::HttpResponse resp) {
    if (resp.m_socket) {
        QTextStream os(resp.m_socket);
        os.setAutoDetectUnicode(true);
        os << "HTTP/1.0 " << resp.m_status << "\r\n";
        for (QMap<QString, QString>::iterator it = resp.m_headerMap.begin();
             it != resp.m_headerMap.end(); ++it) {
            os << it.key() << ": " << it.value() << "\r\n";
        }
        os << "\r\n" << resp.m_body << "\r\n\r\n";
        resp.m_socket->close();
        m_socketMap.erase(m_socketMap.find(resp.m_socket));
    }
}




}
